package com.zzy.rpc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zzy.commons.IOUtils;

public class Client {
	
	private static Log LOG = LogFactory.getLog(Client.class);
	
	private String host;
	private int port;
	private SocketChannel socketChannel;
	private ByteBuffer receiveBuffer = null;
	private ByteBuffer sendBuffer = null;
	private ByteBuffer header = ByteBuffer.allocate(4);
	
	public Client(String host, int port) {
		this.host = host;
		this.port = port;
		init();
	}
	
	private void init() {
		try {
			socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void invoke(Invocation invocation)  {
		try {
			sendBuffer = ByteBuffer.wrap(IOUtils.toByte(invocation));
			IOUtils.channelIO(null, socketChannel, sendBuffer);
			LOG.info("1.client sendBuffer length: " + sendBuffer.capacity());
			
			header.clear();
			IOUtils.channelIO(socketChannel, null, header);
			header.flip();
			int length = header.getInt();
			receiveBuffer = ByteBuffer.allocate(length);
			int count = IOUtils.channelIO(socketChannel, null, receiveBuffer);
			LOG.info("4.client receiveBuffer length: " + receiveBuffer.capacity());
			if (count > 0) {
				Invocation invoc = (Invocation) IOUtils.toObject((receiveBuffer.array()));
				invocation.setResult(invoc.getResult());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setHost(String host) {
		this.host = host;
	}
	
	public String getHost() {
		return host;
	}
	
	public void setPort(int port) {
		this.port = port;
	}
	
	public int getPort() {
		return port;
	}
	
}
